from flask import Flask, render_template, request, redirect, url_for, flash, session
from flask_mail import Mail, Message
from flask_sqlalchemy import SQLAlchemy
import random
import string

app = Flask(__name__)

# 数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost/snipe'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'your-secret-key'

# 邮件配置
app.config['MAIL_SERVER'] = 'smtp.qq.com'  # 使用QQ邮箱服务器
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'your_qq_email@qq.com'  # 你的QQ邮箱
app.config['MAIL_PASSWORD'] = 'your_email_password'  # 邮箱授权码

db = SQLAlchemy(app)
mail = Mail(app)

# 邮箱验证模型
class EmailVerification(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    verify_code = db.Column(db.String(6), nullable=False)
    is_verified = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp())

def generate_verify_code():
    """生成6位验证码"""
    return ''.join(random.choices(string.digits, k=6))

def send_verify_email(email, verify_code):
    """发送验证邮件"""
    try:
        msg = Message('烟蒂绿航站 - 邮箱验证',
                    sender=app.config['MAIL_USERNAME'],
                    recipients=[email])
        msg.body = f'''欢迎加入烟蒂绿航站！
您的验证码是：{verify_code}
请在注册页面输入此验证码完成验证。
验证码有效期为5分钟。
'''
        mail.send(msg)
        return True
    except Exception as e:
        print(f"发送邮件失败: {str(e)}")
        return False

@app.route('/send_code', methods=['POST'])
def send_code():
    """发送验证码接口"""
    email = request.form.get('email')
    if not email:
        return {'success': False, 'message': '请输入邮箱地址'}

    # 生成验证码
    verify_code = generate_verify_code()
    
    # 保存或更新验证记录
    verification = EmailVerification.query.filter_by(email=email).first()
    if verification:
        verification.verify_code = verify_code
        verification.is_verified = False
    else:
        verification = EmailVerification(email=email, verify_code=verify_code)
        db.session.add(verification)
    
    try:
        db.session.commit()
        # 发送验证邮件
        if send_verify_email(email, verify_code):
            return {'success': True, 'message': '验证码已发送到您的邮箱'}
        else:
            return {'success': False, 'message': '发送验证码失败，请稍后重试'}
    except Exception as e:
        db.session.rollback()
        return {'success': False, 'message': str(e)}

@app.route('/verify_code', methods=['POST'])
def verify_code():
    """验证验证码接口"""
    email = request.form.get('email')
    code = request.form.get('verify_code')
    
    if not email or not code:
        return {'success': False, 'message': '请输入邮箱和验证码'}
    
    verification = EmailVerification.query.filter_by(email=email).first()
    if not verification:
        return {'success': False, 'message': '未找到验证记录'}
    
    if verification.verify_code != code:
        return {'success': False, 'message': '验证码错误'}
    
    # 验证成功，更新状态
    verification.is_verified = True
    db.session.commit()
    
    return {'success': True, 'message': '验证成功'}

@app.route('/check_email', methods=['POST'])
def check_email():
    """检查邮箱是否已验证"""
    email = request.form.get('email')
    if not email:
        return {'success': False, 'message': '请输入邮箱地址'}
    
    verification = EmailVerification.query.filter_by(email=email).first()
    if not verification:
        return {'success': False, 'message': '邮箱未验证'}
    
    return {
        'success': True,
        'verified': verification.is_verified
    }

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True, port=5001) 